package com.markus.spring.ioc.dependency.container;

import com.markus.spring.ioc.dependency.domain.User;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Map;

/**
 * 支持注解功能 @link{ApplicationContext} 注解定义Bean
 * @author 14222
 * @date 2021-03-13 14:09
 */
public class AnnotationApplicationContextAsIoCContainerDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 注册扫描类
        applicationContext.register(AnnotationApplicationContextAsIoCContainerDemo.class);
        // 启动上下文容器
        applicationContext.refresh();
        printCollectionBeanByType(applicationContext);
        // 关闭上下文
        applicationContext.close();
    }

    @Bean
    public User user(){
        User user = new User();
        user.setId(2L);
        user.setName("markus");
        return user;
    }

    private static void printCollectionBeanByType(BeanFactory beanFactory) {
        if (beanFactory instanceof ListableBeanFactory){
            ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
            Map<String, User> beansOfType = listableBeanFactory.getBeansOfType(User.class);
            System.out.println(beansOfType);
        }
    }
}
